package com.qfjg.controllers;


import com.qfjg.entity.FileUrl;
import com.qfjg.minioconfig.MinioUtils;
import com.qfjg.myutil.ResultData;
import com.qfjg.service.FileUrlService;
import com.qfjg.webcore.auth.Pass;
import com.qfjg.webcore.common.Utils;
import io.minio.Result;
import io.minio.errors.MinioException;
import io.minio.messages.DeleteError;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Collections;
import java.util.List;

@Tag(name = "Minio", description = "Minio文件上传")
@RequestMapping("/${spring.application.name}/Minio")
@RestController
@Slf4j
public class MinioController {
    @Autowired
    private MinioUtils minioUtils;
    @Autowired
    private FileUrlService fileUrlService;

    @Value("${minio.bucketName}")
    private String bucketName;



    @PostMapping("/upload")
    @Operation(summary = "上传文件")
    @Pass
    public ResultData upload(MultipartFile file) {
        if (file.isEmpty()) {
            return new ResultData<>(440, "文件为空", null);
        }

        // 允许的图片类型
        List<String> allowedTypes = List.of(
                "image/jpeg" // JPEG
        );

        // 获取文件的 MIME 类型
        String fileType = file.getContentType();
        if (!allowedTypes.contains(fileType)) {
            return new ResultData<>(441, "不允许的文件类型", null);
        }

        try {
            List<String> uploadedFiles = minioUtils.upload(new MultipartFile[]{file});
            String fileUrl =  uploadedFiles.get(0);
            fileUrlService.insert(new FileUrl(Utils.uuid(), fileUrl));

            return new ResultData<>(200, "文件上传成功", fileUrl);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultData<>(444, "出现错误: " + e.getMessage(), null);
        }

    }

    @PostMapping("/remove/{fileName}")
    @Operation(summary = "删除文件")
    @Pass
    public ResultData removeFile(@PathVariable String fileName) {
        System.out.println("删除图片：" + fileName);
        try {
            // 从URL中提取文件路径
//            String filePath = url.substring(url.indexOf("/" + bucketName + "/") + ("/" + bucketName + "/").length());
            String filePath = fileName;
            // 调用删除方法
            Iterable<Result<DeleteError>> results = minioUtils.removeObjects(bucketName, Collections.singletonList(filePath));

            // 检查删除结果
            for (Result<DeleteError> result : results) {
                if (result.get() != null) {
                    // 如果有错误，返回错误信息
                    return new ResultData<>(500, "文件删除失败: " + result.get().message(), null);
                }
            }
            // 没有错误，返回成功信息
            return ResultData.SUCCESS();
        } catch (MinioException e) {
            // 捕获Minio异常并返回错误信息
            return new ResultData<>(500, "文件删除失败: " + e.getMessage(), null);
        } catch (Exception e) {
            // 捕获其他异常并返回错误信息
            return new ResultData<>(500, "文件删除失败: " + e.getMessage(), null);
        }
    }


    @GetMapping("/imageStream/{fileName}")
    @Operation(summary = "获取文件流")
    @Pass
    public  ResponseEntity getImageStream(@PathVariable String fileName){
        System.out.println("getImageStream");
        ResponseEntity<byte[]> download = minioUtils.getImageStream(fileName);
        return download;
    }



}

